<template>
  <div class="image_input_box">
    <div
      class="input_box"
      @mousedown="longClickUtil.onDown"
      @mouseup="longClickUtil.onUp"
      @mouseleave="longClickUtil.onLeave"
      :style="{ 'background-image': `url('${imageSrc}')` }"
    >
      <transition-group name="fade">
        <TipsPanel key="upload" v-if="imageSrc === ''" icon="ri-gallery-upload-line" tips="上传图片" />
        <TipsPanel
          key="uploading"
          v-if="progress >= 0"
          :progress="progress"
          icon="ri-gallery-upload-line"
          tips="上传中"
        />
      </transition-group>
    </div>
    <input type="file" ref="inputer" @change="handleChange" />
  </div>
</template>

<script>
import { apis, tipsPromiseHandler } from "../api";
import { reactive, ref, toRefs } from "vue";
import { nException, nSuccess } from "./TipsDialog";
import LongClickUtil from '../utils/LongClickUtil.js'
import ArticleCard from "./ArticleCard.vue";
import TipsPanel from "./TipsPanel.vue";
import Md5Utils from "../utils/Md5Utils.js";

export default {
  components: { TipsPanel, ArticleCard },
  setup() {
    const inputer = ref(null);
    const data = reactive({
      imageSrc: '',
      progress: -1
    })
    const handleChange = () => {
      let file = inputer.value.files[0]

      if (file?.type && file?.type?.indexOf('image') >= 0) {
        URL.revokeObjectURL(data.imageSrc)
        data.imageSrc = URL.createObjectURL(file)

        const form = new FormData()
        form.append('file', file)

        Md5Utils.getFromFile(file).then(md5 => {
          console.log(md5)
          console.log(file?.name)
          apis.preSaveImage(md5, file?.name).then((response) => {
            nSuccess((response?.data?.message) || "请求成功")
          }).catch((error) => {
            nException(error.response?.data?.message || "请求失败")
            let promise = apis.saveImage(form, (progressEvent) => {
              data.progress = progressEvent.loaded / progressEvent.total * 100 | 0
              if (data.progress >= 100) data.progress = -1
            })
            tipsPromiseHandler(promise)
          })
        })
      }
    }
    const selectImage = () => {
      inputer.value.click()
    }
    const clearImage = () => {
      data.imageSrc = ''
    }

    const longClickUtil = LongClickUtil(selectImage, clearImage)
    return { ...toRefs(data), handleChange, longClickUtil, inputer }
  }
}
</script>

<style scoped lang="less">
.image_input_box {
  display: flex;
  margin-left: 20px;

  & .input_box {
    width: 200px;
    height: 120px;
    border-radius: 10px;
    overflow: hidden;
    background-size: contain;
    background-position: center;
    background-repeat: no-repeat;
    background-color: rgba(0, 0, 0, 0.7);
    transition: all 0.3s ease;
    cursor: pointer;
    border: 3px solid black;

    &:hover {
      transform: scale(1.05);
    }

    &:active {
      transform: scale(0.95);
    }
  }

  input {
    display: none;
  }
}
</style>